package com.tiance.demo.ui.page;

import com.tiance.demo.observer.ObserverData;
import com.tiance.demo.observer.ObserverEvent;
import com.tiance.demo.observer.ObserverSystem;
import com.tiance.demo.observer.Publisher;
import com.tiance.demo.service.mysql.bo.Page;
import com.tiance.demo.service.mysql.bo.pageindex.PageIndex;
import com.tiance.demo.service.mysql.utils.ByteUtils;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.web.WebView;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

public class ByteContentPane extends VBox implements Observer {

    private Label ruler = new Label();

    private WebView webView = new WebView();

    public ByteContentPane() {
        ruler.setFont(Font.font("FZYouSongJS 504L"));
        initRuler();

        this.getChildren().addAll(ruler, webView);
        setPrefHeight(240);

        ObserverSystem.registerObserver(ObserverEvent.PAGE_SWITCH, this);
    }

    private void initRuler() {
        List<String> rulerText = new ArrayList<>();
        String result = "";
        for (int i = 0; i < 32; i++) {
            result += String.format("%02d ", i);
        }
        ruler.setText(" " + result);
    }

    @Override
    public void update(Observable o, Object arg) {
        Publisher publisher = (Publisher) o;
        ObserverData transfer = ObserverData.transfer(arg);

        if (publisher.getObserverEvent() == ObserverEvent.PAGE_SWITCH) {
            Page page = (Page) transfer.getData();

            String bytes;
            if (page instanceof PageIndex) {
                PageIndex pageIndex = (PageIndex) page;
                bytes = ByteUtils.bytes2HexStr(pageIndex.getBytes());
            } else {
                bytes = ByteUtils.bytes2HexStr(page.getBytes());
            }

            bytes += " "; //不可少

            StringBuilder sb = new StringBuilder("<body style='background-color: black'><p style='font-family:Consolas,Monaco,monospace'>");

            int byteLength = 3, bytesOneLine = 32, totalBytesOneLine = byteLength * bytesOneLine;
            for (int i = 0; i < bytes.length() / 96; i++) {
                sb.append("<font color='red'>").append(String.format("%06d", i * bytesOneLine)).append("</font>").append("&nbsp;&nbsp;&nbsp;");
                sb.append("<font color='green'>").append(bytes, 96 * i, 96 * i + 8 * 3).append("</font>");
                sb.append("<font color='blue'>").append(bytes, 96 * i + 8 * 3, 96 * i + 16 * 3).append("</font>");
                sb.append("<font color='green'>").append(bytes, 96 * i + 16 * 3, 96 * i + 24 * 3).append("</font>");
                sb.append("<font color='blue'>").append(bytes, 96 * i + 24 * 3, 96 * (i + 1)).append("</font>");
                sb.append("<br />");
            }
            sb.append("</p></body>");
            webView.getEngine().loadContent(sb.toString());
        }
    }
}
